﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Web.Core
{
    public class Authority
    {
        public static bool CheckAuth(string func, bool needauth)
        {
            if (!needauth) return true;
            string admintype = HttpContext.Current.Request.Cookies["AdminUser"]["AdminType"].ToString().Trim();
            if (admintype == null) return false;
            return FuncInAuth(admintype, func);
        }

        public static bool CheckAuthOnAsmx(string func,string id,string session, bool needauth)
        {
            if (!needauth) return true;
            Model.Admins wheremdl = new Model.Admins();
            int userid = 0;
            int.TryParse(id, out userid);
            wheremdl.AdminId = userid;
            wheremdl.SessionKey = session;
            Model.Admins mdl = new BLL.Admins().GetModel(wheremdl);
            if (mdl == null)
            {
                return false;
            }
            else
            {
                return FuncInAuth(mdl.AdminType, func);
            }
        }

        public static bool FuncInAuth(string admintype, string func)
        {
            string authstr = AuthCache(admintype);
            if (authstr.ToUpper().Trim() == "ALL")
                return true;

            try
            {
                string[] authlist = authstr.Split(new char[] { ',' });
                for (int i = 0; i < authlist.Length; i++)
                {
                    string at = authlist[i];
                    if (authlist[i].ToUpper() == func.ToUpper().Trim())
                        return true;
                }
                return false;
            }
            catch
            {
                return false;
            }
        }

        public static string AuthCache(string admintype)
        {
            if (HttpContext.Current.Cache[admintype] != null)
            {
                return HttpContext.Current.Cache[admintype].ToString();
            }
            else
            {
                Model.AdminType wheremdl = new Model.AdminType();
                wheremdl.AdminTypeName = admintype;
                Model.AdminType mdl = new BLL.AdminType().GetModel(wheremdl);
                if (mdl != null)
                {
                    HttpContext.Current.Cache[admintype] = mdl.AdminPowerList;
                    return HttpContext.Current.Cache[admintype].ToString();
                }
                else
                    return "";
            }
        }

        public static void RefreshCache(string admintype)
        {
            if (HttpContext.Current.Cache[admintype] != null)
                HttpContext.Current.Cache[admintype] = null;
            AuthCache(admintype);
        }
    }
}